package cn.iocoder.yudao.module.planet.service.impl;

import cn.iocoder.yudao.module.planet.controller.app.dto.MembershipDTO;
import cn.iocoder.yudao.module.planet.controller.app.dto.MembershipCreateReqDTO;
import cn.iocoder.yudao.module.planet.controller.app.dto.MembershipUpdateReqDTO;
import cn.iocoder.yudao.module.planet.dal.dataobject.MembershipDO;
import cn.iocoder.yudao.module.planet.dal.mapper.MembershipMapper;
import cn.iocoder.yudao.module.planet.service.MembershipService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 成员关系服务实现类
 * 
 * @author 系统生成
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MembershipServiceImpl implements MembershipService {

    @Resource
    private MembershipMapper membershipMapper;

    @Override
    public Long createMembership(MembershipCreateReqDTO createReqDTO) {
        // 构建成员关系DO对象
        MembershipDO membershipDO = new MembershipDO();
        membershipDO.setUserId(createReqDTO.getUserId());
        membershipDO.setPlanetId(createReqDTO.getPlanetId());
        membershipDO.setRole(createReqDTO.getRole());
        membershipDO.setType(createReqDTO.getType());
        // 如果没有提供权限，设置默认权限
        membershipDO.setPermissions(createReqDTO.getPermissions() != null ? 
                createReqDTO.getPermissions() : getDefaultPermissions());
        membershipDO.setCreatedAt(LocalDateTime.now());
        membershipDO.setUpdatedAt(LocalDateTime.now());

        // 插入数据库
        membershipMapper.insert(membershipDO);

        return membershipDO.getId();
    }

    @Override
    public void updateMembership(MembershipUpdateReqDTO updateReqDTO) {
        // 查询成员关系信息
        MembershipDO membershipDO = membershipMapper.selectById(updateReqDTO.getId());
        if (membershipDO == null) {
            throw new RuntimeException("成员关系不存在: " + updateReqDTO.getId());
        }

        // 更新成员关系信息
        membershipDO.setRole(updateReqDTO.getRole());
        membershipDO.setType(updateReqDTO.getType());
        if (updateReqDTO.getPermissions() != null) {
            membershipDO.setPermissions(updateReqDTO.getPermissions());
        }
        membershipDO.setUpdatedAt(LocalDateTime.now());

        // 保存到数据库
        membershipMapper.updateById(membershipDO);
    }

    @Override
    public void deleteMembership(Long id) {
        // 删除成员关系
        membershipMapper.deleteById(id);
    }

    @Override
    public MembershipDTO getMembership(Long id) {
        // 查询成员关系信息
        MembershipDO membershipDO = membershipMapper.selectById(id);
        if (membershipDO == null) {
            return null;
        }

        // 转换为DTO对象
        return convertToDTO(membershipDO);
    }

    @Override
    public List<MembershipDTO> getMembershipListByUserIdAndPlanetId(Long userId, Long planetId) {
        // 查询成员关系列表
        List<MembershipDO> membershipDOList = membershipMapper.selectListByUserIdAndPlanetId(userId, planetId);

        // 转换为DTO列表
        return membershipDOList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<MembershipDTO> getMembershipListByUserId(Long userId) {
        // 查询成员关系列表
        List<MembershipDO> membershipDOList = membershipMapper.selectListByUserId(userId);

        // 转换为DTO列表
        return membershipDOList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public List<MembershipDTO> getMembershipListByPlanetId(Long planetId) {
        // 查询成员关系列表
        List<MembershipDO> membershipDOList = membershipMapper.selectListByPlanetId(planetId);

        // 转换为DTO列表
        return membershipDOList.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public boolean hasPermission(Long userId, Long planetId, String type, String permission) {
        // 查询用户在特定星球和分组类型中的权限
        MembershipDO membershipDO = membershipMapper.selectByUserIdAndPlanetIdAndType(userId, planetId, type);
        if (membershipDO == null) {
            return false;
        }

        Map<String, Boolean> permissions = membershipDO.getPermissions();
        if (permissions == null) {
            return false;
        }

        // 检查是否有指定权限
        return Boolean.TRUE.equals(permissions.get(permission));
    }

    @Override
    public Map<String, Boolean> getPermissions(Long userId, Long planetId, String type) {
        // 查询用户在特定星球和分组类型中的权限
        MembershipDO membershipDO = membershipMapper.selectByUserIdAndPlanetIdAndType(userId, planetId, type);
        if (membershipDO == null) {
            return new HashMap<>();
        }

        return membershipDO.getPermissions() != null ? 
                membershipDO.getPermissions() : new HashMap<>();
    }

    /**
     * 将MembershipDO转换为MembershipDTO
     */
    private MembershipDTO convertToDTO(MembershipDO membershipDO) {
        MembershipDTO membershipDTO = new MembershipDTO();
        membershipDTO.setId(membershipDO.getId());
        membershipDTO.setUserId(membershipDO.getUserId());
        membershipDTO.setPlanetId(membershipDO.getPlanetId());
        membershipDTO.setRole(membershipDO.getRole());
        membershipDTO.setType(membershipDO.getType());
        membershipDTO.setPermissions(membershipDO.getPermissions());
        membershipDTO.setCreatedAt(membershipDO.getCreatedAt());
        membershipDTO.setUpdatedAt(membershipDO.getUpdatedAt());
        return membershipDTO;
    }

    /**
     * 获取默认权限
     */
    private Map<String, Boolean> getDefaultPermissions() {
        Map<String, Boolean> permissions = new HashMap<>();
        permissions.put("view", true); // 默认有查看权限
        permissions.put("edit", false); // 默认没有编辑权限
        permissions.put("delete", false); // 默认没有删除权限
        return permissions;
    }

}